import scrapy

from books.items import BooksItem, BooksItemLoader


class BooksSpider(scrapy.Spider):
    name = "books"
    allowed_domain = ['books.toscrape.com']
    start_urls = ['http://books.toscrape.com/']

    def parse(self, response):
        for li in response.xpath('//ol/li'):
            l = BooksItemLoader(selector=li, response=response)
            l.add_xpath('title', './/h3/a/text()')
            l.add_css('price', '.price_color::text')
            l.add_css('image_urls', 'img::attr(src)')
            yield l.load_item()


class BooksSpider2(scrapy.Spider):
    name = "books2"
    allowed_domain = ['books.toscrape.com']
    start_urls = ['http://books.toscrape.com/']

    def parse(self, response):
        for li in response.xpath('//ol/li'):
            title = li.xpath('.//h3/a/text()').extract_first()
            price = li.css('.price_color::text').extract_first()
            price = float(price[1:])
            image_url = li.css('img::attr(src)').extract_first()
            image_url = response.urljoin(image_url)
            image_urls = [image_url]
            yield dict(title=title, price=price, image_urls=image_urls)
